package controls.historyPicker {
	
	import controls.accountsLineChart.AccountsLineChart;
	import controls.challengeHistory.ChallengeHistoryDatagrid;
	
	import mx.collections.XMLListCollection;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Tree;
	import mx.events.FlexEvent;
	import mx.events.ListEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	/**
	 * @author Brent Kersanske
	 */ 
	public class HistoryPickerClass extends VBox {
		
		private static var COMPETITIONS_MANIFEST:String = "./competitions/Competition_Manifest.xml";
		
		[Bindable]
		public var competitionList:XMLListCollection;
		
		[Bindable]
		public var competitionInventoryService:HTTPService;
		
		[Bindable]
		public var historyTitle:String;
		
		[Bindable]
		public var challenges:ChallengeHistoryDatagrid;
		
		[Bindable]
		public var accounts:AccountsLineChart;		
		
		public function HistoryPickerClass() {
			addEventListener(FlexEvent.CREATION_COMPLETE, handleCreationComplete);
		}
		
		private function handleCreationComplete(event:FlexEvent):void {
			loadCompetitionDates();
		}
		
		/**
		 * 
		 */ 
		private function loadCompetitionDates():void {
			competitionInventoryService.url = COMPETITIONS_MANIFEST;
			competitionInventoryService.send();
		}

		/**
		 * 
		 */ 		
		public function handleHTTPServiceFault(event:FaultEvent):void {
			Alert.show(event.fault.faultString);
			competitionList.removeAll();
		}
		
		/**
		 * 
		 */ 
		public function handleCompetitionDatesResult(event:ResultEvent):void {
			trace("something happened");
			var xmlList:XMLList = XML(event.result).competitions.competition;
            competitionList = new XMLListCollection(xmlList);
		}
		
		/**
		 * 
		 */ 
		public function labelTreeNode(item:Object):String {
			var node:XML = XML(item);
			if(node.localName() == "competition") {
				return node.@date;
			} else if(node.localName() == "gameHistory") {
				return node.@name;
			} else {
				return "Unknown/Error";
			}
		}    
		
		/**
		 * 
		 */ 
		public function initializeNode(event:ListEvent):void {
			var node:XML = XML(Tree(event.target).selectedItem);
			if(node.localName() == "competition") {
				Alert.show(node.@relativePath);
			} else if(node.localName() == "gameHistory") {
				this.challenges.challengesFilePath = node.@challenges;
				this.accounts.playersFilePath	   = node.@players;
				this.historyTitle = node.@name + " on " + node.parent().@date;
			}
		}    
	}
}